﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using EntreeServer.Module;
using EntreeServer.Module.LocalWebApps;
using EntreeServer.Module.Controls;
using EntreeServer.Module.ActionTray;
using Microsoft.SharePoint;

namespace ME.SDK.OfflineSample
{
    [Guid("00fd3316-585e-44d0-8592-ff74c999633c")]
    public class OfflineOrders : EntreeApplication
    {

        public override string PluginPath
        {
            get
            {
                return "/_layouts/images/ME.SDK.OfflineSample/OfflineOrders";
            }
        }

        public override void QueryList(EntreeScopeObject EntreeScope, EntreeListObject output)
        {
            // Only adding a single button to the Online app screen
            // This button will take them offline
            output.ListTitle = "Hello World";
            EntreeApplicationInstance app = new EntreeApplicationInstance(this);
            app.AllowOffline = true;
            var g = output.AddListGroup();
            EntreeListItemTitleIcon i = g.AddListItem<EntreeListItemTitleIcon>();
            i.ClickAction = new EntreeTakeOfflineClickAction(this);
            i.Title = "Airplane Mode!";
            i.Icon = "/_layouts/images/EntreeServer/inc/at/at-offline-32.png";

        }

        public override Dictionary<string, string> DynamicOfflineContent()
        {
            Dictionary<string, string> ret = new Dictionary<string, string>();
            ret.Add("hbico-home", "/_layouts/images/EntreeServer/inc/hbico-home.png");
            ret.Add("hbico-sync", "/_layouts/images/EntreeServer/inc/at/at-sync-32.png");
            ret.Add("hbico-online", "/_layouts/images/EntreeServer/inc/at/at-goonline-32.png");
            ret.Add("hbico-save", "/_layouts/images/EntreeServer/inc/at/at-save-32.png");
            ret.Add("hbico-at", "/_layouts/images/EntreeServer/inc/hbico-at.png");
            ret.Add("bt-delete", "/_layouts/images/EntreeServer/inc/at/at-delete-32.png");

            return ret;
        }

        public override void BuildLocalAppDefinition(ref AppDefinition app)
        {
            #region Create Order Data
            
            // Using Built in functions to create dataset/models from SP Lists
            SPList list = SPContext.Current.Web.Lists["Orders"];
            DataSetCollection dataSets = DataSetCollection.Create(list);
            DataModel dataSetDefs = DataModel.Create(list);

            // Add datasets to the app
            foreach (var ds in dataSets)
            {
                app.DataSets.Add(ds.Key, ds.Value);
            }
            app.DataModel.AddRange(dataSetDefs);
            #endregion

            #region add global user lookup dataset to app
            // Not using this information in the app currently
            // This adds an offline users list
            DataSet users = DataSet.CreateUserInfo(SPContext.Current.Web);
            app.GlobalDataSets.Add(users.DataSetID, users);

            DataSetDefinition userdef = DataSetDefinition.CreateUserInfo(SPContext.Current.Web);
            app.GlobalDataModel.Add(userdef);
            #endregion

            #region Home Screen
            LocalClickActionObject click = null;
            LocalUpdateItemClickAction click_u = null;
            ActionLane al = null;
            ActionItem ai = null;
            BackActionItem ba = null;
            LocalHomeActionItem ha = null;
            ScreenDefinition s = null;
            LocalListGroup g = null;

            //create the home screen
            s = app.AddScreen("Home");
            ha = new LocalHomeActionItem();
            s.HomeBar.ActionItems.Items.Add(ha);
            g = s.AddGroup();
            g.StyleType = LocalStyleType.Static;
            EntreeLocalItemBillboard bb = g.AddListItem<EntreeLocalItemBillboard>();
            bb.InnerHtml = "<b>Welcome to your first offline mobile app!</b>";

            g = s.AddGroup();
            g.StyleType = LocalStyleType.Static;
            g.ListGroupStyle = EntreeListGroupStyles.buttons;

            // Add the button to open up the orders list
            EntreeLocalItemTitle listItem = g.AddListItem<EntreeLocalItemTitle>();
            listItem.Title = "Orders";
            click = new LocalClickActionObject(this);
            click.ScreenID = "Order_List_Screen";
            click.DataSetID = "Orders";
            click.ClickActionType = LocalClickType.Screen;
            click.AnimationStyle = EntreeAnimationStyles.SLIDE_LEFT;
            listItem.ClickAction = click;

            // Add the default buttons for sync etc... to the ActionTray
            al = new ActionLane("SyncActions");
            al.ActionItems.Items.Add(new GoOnlineActionItem(this, ActionItemIconType.SmallIcons));
            al.ActionItems.Items.Add(new SyncOfflineActionItem(this, ActionItemIconType.SmallIcons));
            s.ActionTray.ActionLanes.Items.Add(al);

            #endregion

            #region Order List
            // Create the screen containing the list of orders
            s = app.AddScreen("Order_List_Screen");
            s.ListTitle = "Orders";
            ha = new LocalHomeActionItem();
            s.HomeBar.ActionItems.Items.Add(ha);
            //s.ListStyle = "list";
            g = s.AddGroup();
            g.DataSetID = "Orders";
            g.StyleType = LocalStyleType.Dynamic;
            EntreeLocalItemTitleCaption cItem = g.AddListItem<EntreeLocalItemTitleCaption>();
            cItem.Title = "Customer_TEXT".ToFieldValueToken();
            cItem.Caption = "Product_TEXT".ToFieldValueToken();
            click = new LocalClickActionObject(this);
            click.ScreenID = "Order_Detail_Screen";
            click.ClickActionType = LocalClickType.Detail;
            click.DataSetID = "Orders";
            click.AnimationStyle = EntreeAnimationStyles.SLIDE_LEFT;
            cItem.ClickAction = click;

            // Add a New button to the screen
            al = new ActionLane("NewButton");
            al.ItemStyle = EntreeActionLaneStyles.text_only;
            ai = new ActionItem();
            ai.Title = "New";
            ai.ActionId = "NewAction";
            click = new LocalClickActionObject(this);
            click.ClickActionType = LocalClickType.Detail;
            click.DataSetID = "Orders";
            click.ScreenID = "Order_New_Screen";
            click.TargetContextMenu = true;
            ai.ClickAction = click;
            al.ActionItems.Items.Add(ai);
            s.ActionTray.ActionLanes.Items.Add(al);
            #endregion

            #region Order Details
            // Create the order details screen
            s = app.AddScreen("Order_Detail_Screen");
            s.ListTitle = "Order Detail";
            ha = new LocalHomeActionItem();
            s.HomeBar.ActionItems.Items.Add(ha);
            // Add Back Button
            ba = new BackActionItem();
            ba.Title = "Back";
            click = new LocalClickActionObject(this);
            click.ClickActionType = LocalClickType.Screen;
            click.ScreenID = "Order_List_Screen";
            click.AnimationStyle = EntreeAnimationStyles.SLIDE_RIGHT;
            ba.ClickAction = click;
            s.HomeBar.ActionItems.Items.Add(ba);

            //Add Delete Button
            ai = new ActionItem();
            ai.Title = "Delete";
            ai.ActionId = "DeleteAction";
            ai.IconUrl = "/_layouts/images/EntreeServer/inc/at/at-delete-32.png";
            click_u = new LocalUpdateItemClickAction(this);
            click_u.ClickActionType = LocalClickType.Delete;
            click_u.DataSetID = "Orders";
            click_u.ScreenID = "Order_List_Screen";
            click_u.AnimationStyle = EntreeAnimationStyles.SLIDE_RIGHT;
            click_u.AfterUpdateEvent = new LocalClickActionObject(this)
            {
                DataSetID = "Orders",
                ScreenID = "Order_List_Screen",
                TargetContextMenu = false,
                ClickActionType = LocalClickType.Detail
            };
            ai.ClickAction = click_u;
            s.ActionTray.AddAction(ai);

            // Show the item details
            g = s.AddGroup();
            g.DataSetID = "Orders";
            g.StyleType = LocalStyleType.Detail;
            var detailItem = g.AddListItem<EntreeLocalItemDetailNameValue>();
            detailItem.Name = "Customer";
            detailItem.Value = "Customer_TEXT".ToFieldValueToken();
            detailItem = g.AddListItem<EntreeLocalItemDetailNameValue>();
            detailItem.Name = "Product";
            detailItem.Value = "Product_TEXT".ToFieldValueToken();
            detailItem = g.AddListItem<EntreeLocalItemDetailNameValue>();
            detailItem.Name = "Quantity";
            detailItem.Value = "Quantity".ToFieldValueToken();

            #endregion

            #region Order New
            LocalDropDownList ddl = null;
            // Create the form for new orders
            s = app.AddScreen("Order_New_Screen");
            s.ListTitle = "New Order";
            s.ListStyle = EntreeListStyles.context_menu;

            g = s.AddGroup();
            g.DataSetID = "Orders";
            g.StyleType = LocalStyleType.Detail;

            #region Customer
            // Dropdown list based upon the Customers dataset
            ddl = g.AddFormItem<LocalDropDownList>("Customer");
            ddl.Name = "Customer";
            ddl.Value = "Customer".ToFieldValueToken();
            ddl.DataSetID = "Customers";
            ddl.DataTextField = "Title";
            ddl.DataValueField = "ID";
            ddl.StyleType = LocalStyleType.Dynamic;
            #endregion

            #region Product
            // Product Selection
            ddl = g.AddFormItem<LocalDropDownList>("Product");
            ddl.Name = "Product";
            ddl.Value = "Title".ToFieldValueToken();
            ddl.DataSetID = "Inventory";
            ddl.DataTextField = "Title";
            ddl.DataValueField = "ID";
            ddl.StyleType = LocalStyleType.Dynamic;
            #endregion

            #region Quantity
            // Basic text box
            LocalTextBox tb = g.AddFormItem<LocalTextBox>("Quantity");
            tb.Name = "Quantity";
            tb.Value = "1";

            #endregion

            // Add the save button for the new order
            ai = new ActionItem();
            ai.Title = "Save";
            ai.ActionId = "SaveAction1";
            ai.IconUrl = "/_layouts/images/EntreeServer/inc/at/at-save-32.png";
            click_u = new LocalUpdateItemClickAction(this);
            click_u.ClickActionType = LocalClickType.Update;
            click_u.DataSetID = "Orders";
            click_u.ScreenID = "Order_Detail_Screen";
            click_u.TargetContextMenu = false;
            click_u.AfterUpdateEvent = new LocalClickActionObject(this)
            {
                DataSetID = "Orders",
                ScreenID = "Order_Detail_Screen",
                TargetContextMenu = false,
                ClickActionType = LocalClickType.Detail
            };
            ai.ClickAction = click_u;
            s.ActionTray.AddAction(ai);
            #endregion
        }

        public override void SyncLocalAppDefinition(DataSetCollection data)
        {
            SPContext.Current.Web.AllowUnsafeUpdates = true;
            DataSet ds = data["Orders"];
            foreach (DataSetRow r in ds.Rows)
            {
                // Check for New Items
                if (r["ME_ISNEW"] != null && r["ME_ISNEW"].ToString() == "1")
                {
                    // Make sure the New item wasn't deleted offline
                    if (r["ME_STATUS"] == null || r["ME_STATUS"].ToString() != "-1")
                    {
                        string customer = r["Customer"].ToString().Replace(";", "").Replace("#", "");
                        string product = r["Product"].ToString().Replace(";", "").Replace("#", "");
                        string quantity = r["Quantity"].ToString();

                        SPList orders = SPContext.Current.Web.Lists["Orders"];
                        SPListItem itm = orders.Items.Add();
                        itm["Title"] = "NewItem";
                        itm["Customer"] = customer;
                        itm["Product"] = product;
                        itm["Quantity"] = quantity;
                        itm.Update();
                    }
                }
                // Check for Deleted Items
                else if (r["ME_STATUS"] != null && r["ME_STATUS"].ToString() == "-1")
                {
                    string itmid = r["ID"].ToString();
                    SPList orders = SPContext.Current.Web.Lists["Orders"];
                    orders.Items.DeleteItemById(Convert.ToInt32(itmid));
                    orders.Update();
                }
            }
            SPContext.Current.Web.AllowUnsafeUpdates = false;
        }
        public override string Title
        {
            get { return "Offline Orders"; }
        }
    }
}
